package top.infopub.security.core;


import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Set;

import org.apache.shiro.session.Session;
import org.apache.shiro.session.UnknownSessionException;
import org.apache.shiro.session.mgt.eis.AbstractSessionDAO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import top.infopub.cache.RedisCached;


/**
 * 实现shiro的session共享  通过redis存储
 * @author Awoke
 * @version 2018年9月17日
 * @see RedisShiroSessionDao
 * @since
 */
public class RedisShiroSessionDao extends AbstractSessionDAO {

    private final Logger logger = LoggerFactory.getLogger(getClass());

    /**
     * session前缀
     */
    private String sessionPrefix = "info-";

    private RedisCached cached;

    public RedisShiroSessionDao() {}

    @Override
    public void update(Session session)
        throws UnknownSessionException {
        try {
            logger.debug("更新缓存，ID:{},超时时间{}", session.getId(), session.getTimeout());
            cached.addCachedExpireSec(session.getId().toString(), session,
                getSec(session.getTimeout()));
        }
        catch (Exception e) {
            logger.error(e.getMessage(), e);
        }

    }

    @Override
    public void delete(Session session) {
        try {
            logger.debug("删除缓存，ID:{}", session.getId());
            cached.deleteCached(session.getId().toString());
        }
        catch (Exception e) {
            logger.error(e.getMessage(), e);
        }

    }

    @Override
    public Collection<Session> getActiveSessions() {
        String keys = sessionPrefix + "*";
        List<Session> list = null;
        try {
            logger.debug("取得所有的ActiveSession");
            // TODO getKeys null
            @SuppressWarnings("unchecked")
            Set<Session> allSession = cached.getKeys(keys);
            if (allSession != null) {
                list = new ArrayList<Session>(allSession);
            }
        }
        catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        return list;
    }

    @Override
    protected Serializable doCreate(Session session) {
        Serializable sessionId = session.getId();
        try {
            logger.debug("创建缓存，ID:{}", session.getId());
            super.assignSessionId(session, sessionPrefix + super.generateSessionId(session));
            update(session);
            sessionId = session.getId();
        }
        catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        return sessionId;
    }

    @Override
    protected Session doReadSession(Serializable sessionId) {
        Session session = null;
        try {
            logger.debug("读取缓存，ID:{}", sessionId);
            session = (Session)cached.getCached(sessionId.toString());
        }
        catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        return session;

    }

    public RedisCached getCached() {
        return cached;
    }

    public void setCached(RedisCached cached) {
        this.cached = cached;
    }

    public String getSessionPrefix() {
        return sessionPrefix;
    }

    public void setSessionPrefix(String sessionPrefix) {
        this.sessionPrefix = sessionPrefix;
    }

    private int getSec(long times) {
        return (new Long(times / 1000)).intValue();
    }

}